from sqlite3 import *
from socket import socket
from sys import path as sp
from datetime import datetime
from json import loads
from threading import Thread
from re import findall,compile
from sqlite3 import connect as sqcon

def curs() :
    global db
    db = connect(sp[0]+'\\db.sqlite3')

def log(str):
    print(datetime.now(),str)

def paintBoard(x,y,col):
    #col <- hex
    log('Paint '+str(x)+','+str(y)+','+col)
    con = connect(sp[0]+'\\db.sqlite3')
    curs = con.cursor()
    ans = curs.execute('SELECT MAX(timeindex) FROM board')
    ansrow = None
    for row in ans :
        ansrow = row[0]
        break
    
    curs = con.cursor()
    curs.execute('INSERT INTO board VALUES ('+str(ansrow+1)+','+str(x)+','+str(y)+',\''+col+'\')')
    con.commit()
    return

format = compile(r"\[\s*(\d+)\s*,\s*(\d+)\s*,\s*#([0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f]{6})\s*]")

def socketHandler(sk,addr):
    global ylen,xlen
    cached = 0
    while True :
        rec = sk.recv(1)

        # C = 获取配置
        if rec == b'C' :
            sk.send(bytes('ylen = ['+str(ylen)+']& xlen [ '+ str(xlen) +' ]',encoding='utf-8')) 

        # G = 获取画板状态
        elif rec == b'G' :

            log('GET status')

            nowst = cached

            db = connect(sp[0]+'\\db.sqlite3')
            cs = db.cursor()
            ans = cs.execute('SELECT x,y,col FROM board WHERE timeindex>'+str(nowst)+'')

            for k in ans :
                print('['+str(k[0])+']['+str(k[1])+']<'+k[2]+'>')
                # '['+str(k[0])+']['+str(k[1])+']<'+k[2]+'>'
                sk.send(bytes('['+str(k[0])+']['+str(k[1])+']<'+k[2]+'>',encoding='utf-8'))

            # stop recv
            sk.send(b'E')
            
            ans = cs.execute('SELECT MAX(timeindex) FROM board')
            ansrow = None
            for row in ans :
                ansrow = row[0]
                break
            cached = ansrow
            # strr = "{:016X}".format(int(hex(int(ansrow)),16))
            # sk.send(bytes(strr,encoding='utf-8'))


        # if rec == b'getBoard' :
            
        #     log('GETBOARD !!')
        #     con = sqcon(sp[0]+'\\db.sqlite3')
        #     curs = con.cursor()
            
        #     # x = sk.recv(1024)
        #     x = 1
        #     # x = str(x,encoding='utf-8')
            
        #     ans = curs.execute('SELECT x,y,col FROM board WHERE timeindex>'+str(x))
        #     for i in ans :
        #         print(i)
        #         if i[0] == 1 :
        #             print('['+str(i[1])+','+str(i[2])+','+str(i[3]),']')
        #             sk.send(bytes('['+str(i[1])+','+str(i[2])+','+str(i[3])+']',encoding='utf-8'))
        #             # sk.send(f"[{i[1]},{i[2]},{i[3]}]")
        #     sk.send(b'CloseSession')
        #     sk.close()
        #     return
        # if rec :
        #     # format = [  x , y , (col)  ]
        #     log('message from '+str(addr[0])+':'+str(addr[1])+'  -  '+str(rec,encoding='utf-8'))
        #     ans = findall(format,str(rec,encoding='utf-8'))
        #     for s in ans :
        #         paintBoard(int(s[0]),int(s[1]),str(s[2]))
    
if __name__ == '__main__' :
    curs()

    configfile = open(sp[0]+'\\config.json','r')
    config = loads(configfile.read())

    ylen = int(config['board']['y_maxlen'])
    log('LOAD y_maxlen')
    xlen = int(config['board']['x_maxlen'])
    log('LOAD x_maxlen')
    port = int(config['address']['port'])
    log('LOAD port')
    max_listen = int(config['address']['max_listen'])
    log('LOAD max_listen')

    soc = socket()
    log('CREATE object socket')

    soc.bind(('',port))
    log('object socket bind to port '+str(port))

    soc.listen(max_listen)
    log('START listen,listen set to '+str(max_listen))

    log('waiting for requests...')

    while True :
        sub_sk,addr = soc.accept()
        log('a request from '+str(addr[0])+':'+str(addr[1]))
        t = Thread(target=socketHandler,args=(sub_sk,addr))
        t.setDaemon(1)
        t.start()
        # socketHandler(sub_sk)

    # paintBoard(1,1,'#dddddd')